//
//  ViewController.m
//  PhotoList
//
//  Created by Caijinglong on 2018/9/10.
//  Copyright © 2018 kikt. All rights reserved.
//  some code from https://www.jianshu.com/p/73f67b92465c
//

#import "ViewController.h"
#import <Photos/PHPhotoLibrary.h>
#import <Photos/PHImageManager.h>
#import <Photos/PHAsset.h>
#import <Photos/PHCollection.h>
#import <Photos/PHFetchOptions.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 120, 80, 30);
    [button setTitle:@"获取图片" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(getImgs) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)getImgs {
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    NSMutableArray *dataArray = [NSMutableArray array];
    PHFetchResult *smartAlbumsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    PHAssetCollection *collection = [smartAlbumsFetchResult objectAtIndex:0];
    [dataArray addObject:collection];

    PHFetchResult *smartAlbumsFetchResult1 = [PHAssetCollection fetchTopLevelUserCollectionsWithOptions:fetchOptions];
    for (PHAssetCollection *sub in smartAlbumsFetchResult1) {
        [dataArray addObject:sub];
    }

    PHFetchResult<PHAsset *> *result = [self getCameraRollFetchResulWithAscend:true];
    for (PHAsset *asset in result) {
        NSLog(@"asset = %@", asset);
    }
}

- (PHFetchResult<PHAsset *> *)getCameraRollFetchResulWithAscend:(BOOL)ascend {
    //获取系统相册CameraRoll 的结果集
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0f) {
        fetchOptions.includeAssetSourceTypes = PHAssetSourceTypeUserLibrary;
    }
    fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascend]];
    PHFetchResult *smartAlbumsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    PHFetchResult *fetch = [PHAsset fetchAssetsInAssetCollection:[smartAlbumsFetchResult objectAtIndex:0] options:fetchOptions];
    return fetch;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end